package com.navinfo.platform.flink.cdc.dao;

import com.alibaba.fastjson.JSONObject;
import com.navinfo.platform.flink.cdc.util.DBUtils;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 同步数据--根据主键进行插入或更新的Dao
 * 要求要同步的表必须有主键
 */
public class UpsertDao implements Serializable {


    /**
     * 新增或更新hy_terminal同步过来的lock_car_terminal
     * @param after
     * @throws SQLException
     */
    public void upsertHyFaultDetail(JSONObject after) throws SQLException {
        String sql = "INSERT INTO ods_hy_fault(id,addr,spn,fmi,addr_spn_fmi,fault_type,fault_level,del_flag) " +
                "VALUES (?,?,?,?,?,?,?,?)" +
                "ON DUPLICATE KEY UPDATE " +
                "addr=?,spn=?,fmi=?,addr_spn_fmi=?,fault_type=?,fault_level=?,del_flag=?";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setObject(1, after.getLong("id"));
            statement.setObject(2, after.getLong("addr"));
            statement.setObject(3, after.getLong("spn"));
            statement.setObject(4, after.getLong("fmi"));
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(after.getLong("addr")).append("_").append(after.getLong("spn")).append("_").append(after.getLong("fmi"));
            statement.setObject(5, stringBuffer.toString());
            statement.setObject(6, after.getLong("fault_type"));
            statement.setObject(7, after.getLong("fault_level"));
            statement.setObject(8, after.getInteger("del_flag"));
            //update子句中的
            statement.setObject(9, after.getLong("addr"));
            statement.setObject(10, after.getLong("spn"));
            statement.setObject(11, after.getLong("spn"));
            statement.setObject(12, stringBuffer.toString());
            statement.setObject(13, after.getLong("fault_type"));
            statement.setObject(14, after.getLong("fault_level"));
            statement.setObject(15, after.getInteger("del_flag"));
            statement.executeUpdate();
        }
    }

}
